<script setup>
//这是2V2模式房主进入的文件，被邀请人进入的不是这个页面，位置为1的不一定是房主
import { onMounted, onBeforeUnmount, ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ws from '@/services/websocket'
import { useUserStore } from '@/stores/user'
import { Player } from '@/component/createroom/player.js'
import { useRoomStore } from '@/stores/room'
import click from '@/services/clickSound'
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const emit = defineEmits(['slot-click'])
const owner_id = ref('')
const roomStore = useRoomStore()
const myposition = ref(1)
// 创建大小为4的响应式数组，每个元素都是Player对象
const players = reactive([
  new Player(),
  new Player(),
  new Player(),
  new Player()
])
const stantard = ref([1,2,3,4])
// 四个位置的就绪文案（默认未准备）
const texts = reactive(['未准备', '未准备', '未准备', '未准备'])
const mytext = reactive(['准备', '准备', '准备', '准备'])
//准备好的人数，若其他三人都准备好的时候，再准备就直接开始游戏
const get_ready_num = ref(0)
// 将当前用户信息赋值给第一个玩家
function setCurrentUserAsPlayer() {
  players[0].user_id = userStore.uid
  players[0].nickname = userStore.nickename
  players[0].profile = userStore.profile

}

// 点击函数
function click1() {
  console.log('点击位置', stantard.value[0])
  emit('slot-click', stantard.value[0])
  click.play()
  
}

function click2() {
  console.log('点击位置', stantard.value[1])
  emit('slot-click', stantard.value[1])
  click.play()
}

function click3() {
  console.log('点击位置', stantard.value[2])
  emit('slot-click', stantard.value[2])
  click.play()
}

function click4() {
  console.log('点击位置', stantard.value[3])
  emit('slot-click', stantard.value[3])
  click.play()
}
//当前用户点击了准备，则要根据目前的准备人数，像服务器发起信息。
function onReady(index) {
  //index是从0开始的，是用户实际的位置不是显示的位置。
  console.log('点击准备：位置', index)
  // 无论是否准备都向服务器发送 ready
  try {
    const payload = {
      genre: 3,
      type: 'ready',
      uid: userStore.uid,
      cid: roomStore.room_id,
      position: index+1
    }
    ws.send(JSON.stringify(payload))
    console.log('发送准备：', payload)
  } catch (e) {
    console.error('发送准备失败：', e)
  }
  //判断当前位置是否已经准备
  if(mytext[index] === '准备'){
    //当前准备了需要根据人数判断是否可以开始游戏
    mytext[index] = '已准备' 
    get_ready_num.value++   
    if(get_ready_num.value === 4){
      //可以开始游戏
      //向服务器发起开始游戏信息
      try {
        const startPayload = {
          genre: 4,
          type: 'start',
          cid: roomStore.room_id
        }
        ws.send(JSON.stringify(startPayload))
        console.log('发送开始武将选择：', startPayload)
      } catch (e) {
        console.error('发送开始失败：', e)
      }
    }
  }
  //用户在取消准备，取消准备
  else if(mytext[index] === '已准备')
  {
    get_ready_num.value--;  
    mytext[index] = '准备'
  }
}
//向服务器发送创建房间
function sendCreateRoom() {
  // 向服务器发送创建房间请求
  const payload = {
      genre: 3,
      type: 'createroom',
      roomtype: '2v2',
      uid: userStore.uid,
      profile: userStore.profile,
      nickname: userStore.nickename
    }
    owner_id.value = userStore.uid
    try {
      ws.send(JSON.stringify(payload))
      console.log('发送创建房间请求:', payload)
    } catch (error) {
      console.error('发送创建房间请求失败:', error)
    }
}

/*页面启动：*/
/*首先判断参数，是房主创建还是是好友邀请进来的*/
/*若是房主则需要发送创建房间的消息*/
/*然后需要注册网络函数*/

onMounted(() => {
  console.log('choose-friend-2v2')
  console.log('收到路由参数 model =', route.query.model)
  // 注册网络回调：创建房间
  ws.on(3, 'createroom', Getroom)
  // 注册：加入房间回调
  ws.on(3, 'joinin', onJoinIn)
  // 注册：有人退出房间回调
  ws.on(3, 'hadleft', onHadLeft)
  // 注册：准备状态变更回调
  ws.on(3, 'changeready', onChangeReady)
  // 注册：所有人开始回调
  ws.on(4, 'allstart', onAllStart)

  
  if(route.query.model === 'create2v2')
  {
    //创建2v2房间
    // 设置当前用户为第一个玩家
    setCurrentUserAsPlayer()
    sendCreateRoom()
  }
  else if(route.query.model === 'invited2v2')
  {
    //被邀请2v2房间
    //首先要根据自己的位置设置座位分布
    //其次要显示所有人的准备信息和其他信息
    //最后要把自己的信息显示出来
    try {
      const raw = route.query.room_data
      if (typeof raw === 'string' && raw.length > 0) {
        const decoded = decodeURIComponent(raw)
        const parsed = JSON.parse(decoded)
        console.log('invited2v2 room_data:', parsed)

        //我的位置（转为数字）
        myposition.value = Number(route.query.position)
        //当前的rid
        const rid = route.query.rid
        roomStore.setRoomId(String(rid))
        //parsed是解析之后的字符串
        //更新响应数据players
        for(let i = 0; i < parsed.length; i++){
          console.log("parsed: ",parsed[i])
          const idx = Number(parsed[i].position) - 1
          if (idx >= 0 && idx < players.length) {
            players[idx].user_id = parsed[i].uid || parsed[i].user_id
            players[idx].nickname = parsed[i].nickname
            players[idx].profile = parsed[i].profile
            //用户已经准备了
            if(parsed[i].ready===true){
              texts[idx] = '已准备'
              get_ready_num.value++;
            }
            else{
              texts[idx] = "未准备"
            }
          }
        }
        //更新自己的数据
        const myIdx = Number.isFinite(myposition.value) ? myposition.value - 1 : -1
        if (myIdx >= 0 && myIdx < players.length) {
          players[myIdx].user_id = userStore.uid
          players[myIdx].nickname = userStore.nickename
          players[myIdx].profile = userStore.profile
        }

        //根据自己的位置修改映射信息
        if(myposition.value===1){stantard.value=[1,2,3,4]}
        else if(myposition.value===2){stantard.value=[2,3,4,1]}
        else if(myposition.value===3){stantard.value=[3,4,1,2]}
        else if(myposition.value===4){stantard.value=[4,1,2,3]}
        else {console.log("映射设置出错");console.log("position：",typeof(position),position)}
        console.log("当前映射：",stantard.value)

      }
    } catch (e) {
      console.error('解析 room_data 失败:', e)
    }
    // 取出位置与房间ID
    console.log('invited2v2 position:', route.query.position, 'rid:', route.query.rid)
  }
})

onBeforeUnmount(() => {
  // 保存 stantard 和 mypos 到全局状态
  roomStore.setStantard(stantard.value)
  roomStore.setMyPos(myposition.value)
  
  ws.off(3, 'createroom')
  ws.off(3, 'joinin')
  ws.off(3, 'hadleft')
  ws.off(3, 'changeready')
  ws.off(4, 'allstart')
})
//创建房间成功,设置房间id,如果不是房主就收不到这个消息
function Getroom(message){
  // 期望格式：{ genre:3, type:'createroom', state, message, data:{ rid, roomtype, owner_id } }
  console.log('message',message)
  if (Number(message?.state) !== 0) {
    console.error('创建房间失败：', message?.message)
    roomStore.setRoomId("创建房间失败！")
    return
  }
  const rid = message?.data?.rid
  if (rid) {
    roomStore.setRoomId(String(rid))
    console.log('房间创建成功，rid =', roomStore.room_id)
  }
}

// 有人加入房间的网络回调
function onJoinIn(message) {
  // 根据服务器返回的信息更新对应位置的玩家
  try {
    console.log("有人加入房间，位置：",message.pos)
    const pos = Number(message?.pos)
    if (!pos || pos < 1 || pos > players.length) return
    const targetIndex = pos - 1
    const uid = message?.uid || message?.user_id || message?.from_uid
    const nickname = message?.nickname
    const profile = message?.profile
    if (uid) players[targetIndex].user_id = String(uid)
    if (typeof nickname === 'string') players[targetIndex].nickname = nickname
    if (typeof profile === 'string') players[targetIndex].profile = profile
  } catch (_) {}
}

// 有人退出房间的网络回调
function onHadLeft(message) {
  console.log("删除之前")
  console.log(players)
  try {
    console.log("有人离开房间",message);
    const uid = message?.uid 
    if (!uid) return
    for (let i = 0; i < players.length; i++) {
      console.log("第",i,"次循环")
      if (players[i]._user_id === uid) {
        console.log("有人离开房间：",players[i]._user_id," 位置：",i)
        players[i].user_id =''
        players[i].nickname = ''
        players[i].profile = ''

        //若当前用户已经准备了，就要取消它的准备状态
        if(text[i] === '已准备'){
          texts[i] = '准备'
          get_ready_num.value--;
        }
        break
      }
    }
    console.log("删除之后")
    console.log(players)
  } catch (_) {}
}

// 准备状态变更回调
function onChangeReady(message) {
  try {
    const pos = Number(message?.position)
    if (!Number.isFinite(pos)) return
    const idx = pos - 1
    if (idx < 0 || idx >= texts.length) return
    if (texts[idx] === '未准备') {
      texts[idx] = '已准备'
      get_ready_num.value++
    } else {
      texts[idx] = '未准备'
      get_ready_num.value = Math.max(0, get_ready_num.value - 1)
    }
  } catch (_) {}
}

// 所有人开始回调（开局）
function onAllStart(message) {
  try {
    console.log('收到 allstart：', message)
    router.replace('/loading-game')
  } catch (_) {}
}


</script>

<template>
  <div class="choose-friend-2v2">
      <div class="top">
        <div class="left"></div>
        <div class="center">
          <!--上中的位置-->
          <div v-if="!players[stantard[2]-1].user_id" class="add-player" @click="click3">
            <img src="http://117.72.17.45:5500/data/icons/加.png" alt="加" />
            <span class="position-number">{{ stantard[2] }}号位置</span>
          </div>
          <div v-else class="player-card">
            <img class="player-avatar" :src="`http://117.72.17.45:5500/data/profiles/${players[stantard[2]-1].profile || 'default.webp'}`" :alt="players[stantard[2]-1].nickname || 'avatar'" />
            <div class="player-name">{{ players[stantard[2]-1].nickname || '玩家' }}</div>
            <button v-if="players[stantard[2]-1].user_id === userStore.uid" class="ready-btn" @click="onReady(stantard[2]-1)">{{ mytext[stantard[2]-1] }}</button>
            <div v-else class="ready-text">{{ texts[stantard[2]-1] }}</div>
          </div>
        </div>
        <div class="right"></div>
      </div>
      <div class="middle">
        <div class="left">
          <!--中左的位置-->
          <div v-if="!players[stantard[3]-1].user_id" class="add-player" @click="click4">
            <img src="http://117.72.17.45:5500/data/icons/加.png" alt="加" />
            <span class="position-number">{{ stantard[3] }}号位置</span>
          </div>
          <div v-else class="player-card">
            <img class="player-avatar" :src="`http://117.72.17.45:5500/data/profiles/${players[stantard[3]-1].profile || 'default.webp'}`" :alt="players[stantard[3]-1].nickname || 'avatar'" />
            <div class="player-name">{{ players[stantard[3]-1].nickname || '玩家' }}</div>
            <button v-if="players[stantard[3]-1].user_id === userStore.uid" class="ready-btn" @click="onReady(stantard[3]-1)">{{ mytext[stantard[3]-1] }}</button>
            <div v-else class="ready-text">{{ texts[stantard[3]-1] }}</div>
          </div>
        </div>
        <div class="center">
          <img src="http://117.72.17.45:5500/data/icons/圆桌.png" alt="圆桌" />
        </div>
        <div class="right">
          <!--中右的位置-->
          <div v-if="!players[stantard[1]-1].user_id" class="add-player" @click="click2">
            <img src="http://117.72.17.45:5500/data/icons/加.png" alt="加" />
            <span class="position-number">{{ stantard[1] }}号位置</span>
          </div>
          <div class="player-card" v-else>
            <img class="player-avatar" :src="`http://117.72.17.45:5500/data/profiles/${players[stantard[1]-1].profile || 'default.webp'}`" :alt="players[stantard[1]-1].nickname || 'avatar'" />
            <div class="player-name">{{ players[stantard[1]-1].nickname || '玩家' }}</div>
            <button v-if="players[stantard[1]-1].user_id === userStore.uid" class="ready-btn" @click="onReady(stantard[1]-1)">{{ mytext[stantard[1]-1] }}</button>
            <div v-else class="ready-text">{{ texts[stantard[1]-1] }}</div>
          </div>
        </div>
      </div>
      <div class="bottom">
        <div class="left"></div>
        <div class="center">
          <!--下中的位置-->
          <div v-if="!players[stantard[0]-1].user_id" class="add-player" @click="click1">
            <img src="http://117.72.17.45:5500/data/icons/加.png" alt="加" />
            <span class="position-number">{{ stantard[0] }}号位置</span>
          </div>
          <div class="player-card" v-else>
            <img class="player-avatar" :src="`http://117.72.17.45:5500/data/profiles/${players[stantard[0]-1].profile || 'default.webp'}`" :alt="players[stantard[0]-1].nickname || 'avatar'" />
            <div class="player-name">{{ players[stantard[0]-1].nickname || '玩家' }}</div>
            <button v-if="players[stantard[0]-1].user_id === userStore.uid" class="ready-btn" @click="onReady(stantard[0]-1)">{{ mytext[stantard[0]-1] }}</button>
            <div v-else class="ready-text">{{ texts[stantard[0]-1] }}</div>
          </div>
        </div>
        <div class="right"></div>
      </div>
  </div>
</template>

<style scoped>
.choose-friend-2v2 {
  width: 100%;
  height: 90%;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 12px;
  display: grid;
  grid-template-rows: 1fr 3fr 1fr; /* 上中下 */
  gap: 8px;
  padding: 8px;
  box-sizing: border-box;
}
.top, .bottom {
  display: grid;
  grid-template-columns: 1fr 3fr 1fr; /* 左中右 */
  gap: 8px;
}
.middle {
  display: grid;
  grid-template-columns: 1fr 3fr 1fr; /* 左中右 */
  gap: 8px;
}
.left, .right {
  background: rgba(255,255,255,0.3);
  border-radius: 8px;
}
.top .center, .bottom .center {
  background: rgba(255,255,255,0.3);
  border-radius: 8px;
}
.center {
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255,255,255,0.3);
  border-radius: 8px;
}
.center img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
.add-player {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  cursor: pointer;
  position: relative;
}
.add-player img {
  width: 40px;
  height: 40px;
  object-fit: contain;
}
.position-number {
  position: absolute;
  left: 8px;
  top: 8px;
  color: #333;
  font-weight: bold;
  font-size: 28px;
}

.player-card {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
.player-avatar {
  width: 64px;
  height: 64px;
  border-radius: 8px;
  object-fit: cover;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
.player-name {
  color: #333;
  font-weight: 700;
}

.ready-btn {
  margin-top: 4px;
  padding: 6px 12px;
  border: none;
  border-radius: 8px;
  background: #1677ff;
  color: #fff;
  cursor: pointer;
}
.ready-text {
  margin-top: 4px;
  color: #555;
}
</style>